package com.example.forum.controller;

import com.example.forum.dto.ArticleCreate;
import com.example.forum.dto.Pagination;
import com.example.forum.dto.PostDtoList;
import com.example.forum.dto.ReplyCreate;
import com.example.forum.entity.Article;
import com.example.forum.entity.Favo;
import com.example.forum.entity.Reply;
import com.example.forum.entity.User;
import com.example.forum.interceptor.UserContext;
import com.example.forum.mapper.ArticleMapper;
import com.example.forum.mapper.ReplyMapper;
import com.example.forum.mapper.UserMapper;
import com.example.forum.util.JsonResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;



@RestController
    public class PostController {

    @Resource
    UserMapper userMapper;
    @Resource
    ArticleMapper articleMapper;
    @Resource
    ReplyMapper replyMapper;

    @PostMapping("/api/post/create")
    public JsonResult<Object> createPost(@Valid ArticleCreate articleCreate) {
        Integer categoryId = articleCreate.getCategoryId();
        if (categoryId == null) {
            categoryId = 0;
        }
        String content = articleCreate.getContent();
        Integer status = articleCreate.getStatus();
        if (status == null) {
            status = 0;
        }
        System.out.println(articleCreate.getTag());
        String tag = articleCreate.getTag();
        if(Objects.equals(tag, "")){tag=null;}
        String title = articleCreate.getTitle();
        String username = UserContext.getUser().getUsername();

        Integer userId = userMapper.selectUser(username).getId();
        String category=new String();
        switch (categoryId){
            case 1:category="其他";break;
            case 2:category="提问";break;
            case 3:category="分享";break;
            case 4:category="建议";break;
            case 5:category="讨论";break;
            case 6:category="公告";break;
            case 7:category="动态";break;
            default:category="";break;
        }

        Article article = Article.builder().userId(userId).title(title).content(content).tag(tag).categoryId(categoryId).category(category).status(status).build();
        System.out.println(article);
        Integer i = articleMapper.insert(article);
        if (!(i == 1)) {
            return new JsonResult<>("error", "新增文章失败");
        }
        return new JsonResult<>("SUCCESS", "新增成功", "");
    }

    @PostMapping("api/post/delete")
    public JsonResult<Object> delete(HttpServletRequest request) {
        if(request.getParameter("id")==null){ return new JsonResult<>("error","articleId错误");}
        Integer id = Integer.valueOf(request.getParameter("id"));
        //根据文章id查userid，与上下文id匹配为同一用户即可删除，否则无此权限；
        Integer userId = articleMapper.select(id).getUserId();
        if (userId == null) {
            return new JsonResult<>("", "未知错误");
        }
        Integer UID = UserContext.getUser().getId();
        //UID=2;
        if (!userId.equals(UID)) {
            return new JsonResult<>("", "权限不够，此文章不是您的");
        }
        Integer i = articleMapper.delete(id);
        if (i != 1) {
            return new JsonResult<>("error", "删除失败");
        }
        return new JsonResult<>("SUCCESS", "删除成功", "");
    }

    @PostMapping("/api/post/reply")
    public JsonResult<Object> replyCreate(@Valid ReplyCreate replyCreate) {
        System.out.println(123);
        Integer id = replyCreate.getId();
        String content = replyCreate.getContent();
        if((UserContext.getUser().getId())==0){ return new JsonResult<>("error","未登录");}
        Integer userId = UserContext.getUser().getId();
        // userId=1;
        Reply reply = Reply.builder().articleId(id).content(content).userId(userId).build();
        System.out.println(reply);
        Integer rows = replyMapper.insert(reply);
        try {
            articleMapper.replyNum(id);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (rows != 1) {
            return new JsonResult<>("", "新曾回复失败");
        }
        return new JsonResult<>("SUCCESS", "新增成功", "");
    }

    //收藏和点赞
    @PostMapping("/api/post/favorite")
    public JsonResult<Object> favorite(HttpServletRequest request) {
        if (request.getParameter("id")== null) {
            return new JsonResult<>("error", "articleId错误");
        }
        Integer id = Integer.valueOf(request.getParameter("id"));
        int UID = UserContext.getUser().getId();
        Favo favo1 = userMapper.favoSet(UID, id);
        if (favo1 == null) {
            Favo favo = Favo.builder().userId(UID).articleId(id).favorite(true).build();
            Integer a = userMapper.favoInsert(favo);
            if (a == 1) {
                articleMapper.favNum(id);
                Map<String,Object>data=new HashMap<>();
                Article article=articleMapper.select(id);
                int userId=UserContext.getUser().getId();
                Favo favo5=userMapper.selectFavo(userId,id);
                data.put("favoriteBool",favo5.isFavorite());
                data.put("favoriteCount",article.getFavoriteCount());
                return new JsonResult<>("Success", data, "");
            }
        }
        assert favo1 != null;
        System.out.println(favo1.isFavorite());
        if (!favo1.isFavorite()) { articleMapper.favNum(id);
        } else {
            articleMapper.favNumJian(id);
        }
        Favo favo2 = Favo.builder().userId(UID).articleId(id).favorite(!favo1.isFavorite()).build();
        userMapper.favoUpdate(favo2);
        Map<String,Object>data=new HashMap<>();
        Article article=articleMapper.select(id);
        int userId=UserContext.getUser().getId();
        Favo favo=userMapper.selectFavo(userId,id);
        data.put("favoriteBool",favo.isFavorite());
        data.put("favoriteCount",article.getFavoriteCount());
        return new JsonResult<>("Success", data, "");


        /**
         * 收藏表（喜欢表） 一个userid articleId favorite的表
         * 文章表收藏+1
         * 收藏表置true  map
         *
         */

    }

    @PostMapping("/api/post/like")
    public JsonResult<Object> lov(HttpServletRequest request) {
        if(request.getParameter("id")==null){ return new JsonResult<>("error","articleID错误");}
        Integer id = Integer.valueOf(request.getParameter("id"));
        int UID=UserContext.getUser().getId();
        Integer uid=UID;
        System.out.println(uid);
        Favo favoLov = userMapper.favoSet(UID, id);
        if (favoLov == null) {
            Favo favo = Favo.builder().userId(UID).articleId(id).love(true).build();
            Integer a = userMapper.favoInsert(favo);
            if (a == 1) {articleMapper.loveNum(id);
                Map<String,Object>data=new HashMap<>();
                Article article=articleMapper.select(id);
                int userId=UserContext.getUser().getId();
                Favo favo5=userMapper.selectFavo(userId,id);
                data.put("likeBool",favo5.isLove());
                data.put("likeCount",article.getLikeCount());
                return new JsonResult<>("Success", data, "");
            }
        }
        assert favoLov != null;//断言
        if (!favoLov.isLove()) {articleMapper.loveNum(id);
        } else {
            articleMapper.loveNumJian(id);
        }
        Favo favoLov2 = Favo.builder().userId(UID).articleId(id).love(!favoLov.isLove()).build();
        userMapper.loveUpdate(favoLov2);


        Map<String,Object>data=new HashMap<>();
        Article article=articleMapper.select(id);
        int userId=UserContext.getUser().getId();
        Favo favo=userMapper.selectFavo(userId,id);
        data.put("likeBool",favo.isLove());
        data.put("likeCount",article.getLikeCount());
        return new JsonResult<>("SUCCESS", data, "");
    }

    public static class Category{
        public Integer id;
        public String name;
        //为什么在这不能用private
        public Integer status;
        public Date createdAt;
        public Category(Integer id, String name, Integer status, Date createdAt) {
            this.id = id;
            this.name = name;
            this.status = status;
            this.createdAt = new Date();
        }
    }
    //种类id
    @GetMapping("/api/post/categories")
    public JsonResult<Object> categories() {
        List<Category> classMes=new ArrayList<>();
        classMes.add(new Category(1,"其他",1,new Date()));
        classMes.add(new Category(2,"提问",1,new Date()));
        classMes.add(new Category(3,"分享",1,new Date()));
        classMes.add(new Category(4,"建议",1,new Date()));
        classMes.add(new Category(5,"讨论",1,new Date()));
        classMes.add(new Category(6,"公告",1,new Date()));
        classMes.add(new Category(7,"动态",1,new Date()));
        classMes.add(new Category(0,"默认",1,new Date()));
        return new JsonResult<>("SUCCESS",classMes);
    }

    //种类ID对应标签名字
    @GetMapping("/api/post/categoryId")
    public JsonResult<Object> categories(HttpServletRequest request) {
        Integer id = Integer.valueOf(request.getParameter("id"));
        System.out.println(id);
        switch (id) {
            case 1:return new JsonResult<>("","1:其他","");
            case 2:return new JsonResult<>("","2:提问","");
            case 3:return new JsonResult<>("","3:分享","");
            case 4:return new JsonResult<>("","4:建议","");
            case 5:return new JsonResult<>("","5:讨论","");
            case 6:return new JsonResult<>("","6:公告","");
            case 7:return new JsonResult<>("","7:动态","");
            default:return new JsonResult<>("","0:默认","");
        }
    }

    //根据文章集查对应user  postdtolist
    public List<PostDtoList> list(List<Article> articles){
        PostDtoList postDtoList1 = new PostDtoList();
        List<PostDtoList>postDtoList=new ArrayList<>();
        for(Article article:articles){
            User user =userMapper.selectUserByid(article.getUserId());
            Favo favo=userMapper.favoSet(article.getUserId(),article.getId());
            if(favo==null){
                try {
                    postDtoList1= new PostDtoList(user.getAvatar(), false,user.getLevel(),false, user.getNickname(),user.getId(),user.getUsername(),article);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }else{
                postDtoList1= new PostDtoList(user.getAvatar(),favo.isFavorite(),user.getLevel(),favo.isLove(), user.getNickname(),user.getId(),user.getUsername(),article);
            }
            postDtoList.add(postDtoList1);
        }

        return postDtoList;

    }


    //文章列表查询，内容查询
    @GetMapping("/api/post/list")
    public JsonResult<Object> listPost(Pagination pagination){
        List<Article>articles=articleMapper.findArticles(pagination);
        pagination.setTotal(articleMapper.num());
//        PostDtoList postDtoList1 = new PostDtoList();
//        List<PostDtoList>postDtoList=new ArrayList<>();

//        for(Article article:articles){
//            User user =userMapper.selectUserByid(article.getUserId());
//            Favo favo=userMapper.favoSet(article.getUserId(),article.getId());
//            if(favo==null){
//                try {
//                    postDtoList1= new PostDtoList(user.getAvatar(), false,user.getLevel(),false, user.getNickname(),user.getId(),user.getUsername(),article);
//                } catch (Exception e) {
//                    throw new RuntimeException(e);
//                }
//            }else{
//                postDtoList1= new PostDtoList(user.getAvatar(),favo.isFavorite(),user.getLevel(),favo.isLove(), user.getNickname(),user.getId(),user.getUsername(),article);
//            }
//            postDtoList.add(postDtoList1);
//        }
        Map<String ,Object>data= new HashMap<>();
        List<PostDtoList> postDtoList=list(articles);
        data.put("postDtoList",postDtoList);
        data.put("postSearchDto",pagination);
        return new JsonResult<>("SUCCESS",data);

        /**
         *     protected int page;//当前页面
         *     protected int limit;//页面条数
         *     protected long total;//总数
         *     protected Integer category;//种类id
         *     protected Date createdBegin;//开始时间
         *     protected Date createdEnd;//结束时间
         *     protected Integer recommend;
         *     protected Integer status;//状态（个人可见或人类可见）
         *     protected String tag;//标签
         *     protected String title;//标题
         *     protected Integer userId;//用户id
         *     protected String username;//用户名
         */
    }
    @GetMapping("/api/post/view")
    public JsonResult<Object>view(HttpServletRequest request){
        //判断又饿米有userID 有就去查favo表，，，查询fav状态true   or false，if有，data.add
        Integer id = Integer.valueOf(request.getParameter("id"));
        Article article=articleMapper.select(id);
        Map<String ,Object>data= new HashMap<>();
        System.out.println(article.getFavorite());
        data.put("favorite:",article.getFavorite());
        data.put("like",article.getLike());
        User user =userMapper.selectUserByid(article.getUserId());
        PostDtoList postDto=new PostDtoList(user.getAvatar(), article.getFavorite(),user.getLevel(),
                article.getLike(), user.getNickname(), user.getId(), user.getUsername(), article);
        List<Article> articles=articleMapper.selects(id);
        articleMapper.viewNum(id);
        data.put("postDto",postDto);
        return new JsonResult<>("SUCCESS",data);
    }

    @GetMapping("/api/post/getTagOrder")
    public JsonResult<Object>getTagOrder(HttpServletRequest request){
        try {
            int num = Integer.parseInt(request.getParameter("hotTagNumber"));
            //此处用string集合接受是bug
            List<String>data1=articleMapper.findTag();
            LinkedHashSet<String>data3=new LinkedHashSet<>(data1);
            ArrayList<String>data4=new ArrayList<>(data3);
            String [] data=new String[num];
            for(int i=0;i<num;i++){
                if(i<data4.size()){
                    data[i]= data4.get(i);
                }else{
                    data[i]= "";
                }
            }
            return new JsonResult<>("SUCCESS",data);
        }
        catch(Exception e){
            throw new RuntimeException("请输入热门标签数量");
        }
    }
    @GetMapping("/api/post/my")
    public JsonResult<Object>myPost(){
        Integer id=UserContext.getUser().getId();
        List<Article>articles=articleMapper.mypost(id);

        Map<String ,Object>data= new HashMap<>();
        List<PostDtoList> postDtoList=list(articles);
        data.put("postDtoList",postDtoList);
        Pagination pagination=new Pagination();
        data.put("postSearchDto",pagination);
        return new JsonResult<>("SUCCESS",data);
    }
    @GetMapping("/api/post/replyList")
    public JsonResult<Object>viewReplies(HttpServletRequest request){
        if(request.getParameter("id")==null){ return new JsonResult<>("error","请输入文章id");}

        Integer id = Integer.valueOf(request.getParameter("id"));
        Article article=articleMapper.select(id);
        System.out.println(id);
        Pagination pagination=Pagination.builder().limit(5).page(1).total(article.getReplyCount()).build();
        Map<String ,Object>data= new HashMap<>();
        data.put("pagination",pagination);
        List<Reply>replys=replyMapper.replyList(id);
        List<PostDtoList> postDtoLists=new ArrayList<>();
        for(Reply reply:replys){
            User user=userMapper.selectUserByid(reply.getUserId());
            PostDtoList postDtoList1=new PostDtoList(user.getAvatar(),false, user.getLevel(), false, user.getNickname(),
                    user.getId(), user.getUsername(), reply);
            postDtoLists.add(postDtoList1);
        }
        data.put("replyList",postDtoLists);

        return new JsonResult<>("SUCCESS",data);
    }
    //周榜
    @GetMapping("/api/post/month")
    public JsonResult<Object>month(){
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-01 00:00:00");
        String month=simpleDateFormat.format(new Date());

        System.out.println(month);
        Date month1= null;
        try {
            month1 = simpleDateFormat.parse(month);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        List<Article>articles= null;
        try {
             articles= articleMapper.selectMonth(month1);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Map<String ,Object>data= new HashMap<>();
        List<PostDtoList> postDtoList=list(articles);
        data.put("postDtoList",postDtoList);
        Pagination pagination=new Pagination();
        data.put("postSearchDto",pagination);
        return new JsonResult<>("SUCCESS",data);
    }
    @GetMapping("/api/post/week")
    public JsonResult<Object>week(){
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd 00:00:00");
        Calendar cal=Calendar.getInstance();
        Date date=new Date();
        cal.setTime(date);
        //获得当前时间是一个星期的第几天
        int dayWeek=cal.get(Calendar.DAY_OF_WEEK);
        System.out.println(dayWeek);
        if(1==dayWeek){
            cal.add(Calendar.DAY_OF_MONTH,-1);
        }
        //设置一个星期的第一天，按中国的习惯一个星期的第一天是星期一
        cal.setFirstDayOfWeek(Calendar.MONDAY);
        //获取当前日期是一个星期的第几天
        int day=cal.get(Calendar.DAY_OF_WEEK);
        //根据日历的规则，给当前日期减去星期几与一个星期第一天的差值；
        System.out.println("相减得：");
        System.out.println(cal.getFirstDayOfWeek()-day);
        //如果周一，则返回上周一
        if(cal.getFirstDayOfWeek()-day==0){
            cal.add(Calendar.DATE,-7);
        }else {
            cal.add(Calendar.DATE, cal.getFirstDayOfWeek() - day);
        }
        Date month1= null;
        try {
            month1 = simpleDateFormat.parse(simpleDateFormat.format(cal.getTime()));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }




        System.out.println("周榜"+month1);
        List<Article>articles= null;
        try {
            articles = articleMapper.selectMonth(month1);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        Map<String ,Object>data= new HashMap<>();
        List<PostDtoList> postDtoList=list(articles);
        data.put("postDtoList",postDtoList);
        Pagination pagination=new Pagination();
        data.put("postSearchDto",pagination);
        return new JsonResult<>("SUCCESS",data);
    }
    @GetMapping("/api/post/myFavorite")
    public JsonResult<Object> myFavorite(){
        //获取userid 和favorite=1  查找对应的articleId根据id查文章
        int userId=UserContext.getUser().getId();
        List<Integer> articleId=userMapper.selectArticleId(userId);
        System.out.println(articleId);
        List<Article>articles=new ArrayList<>();
        for(Integer id:articleId){
            Article article=articleMapper.select(id);
            articles.add(article);
        }
        Map<String ,Object>data= new HashMap<>();
        List<PostDtoList> postDtoList=list(articles);
        Pagination pagination=new Pagination();
        data.put("postDtoList",postDtoList);
        data.put("postSearchDto",pagination);

        return new JsonResult<>("SUCCESS",data);
    }


}